package lembrete.core.report;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import lembrete.core.beans.Grupo;
import lembrete.core.beans.Usuario;
import lembrete.core.exceptions.ExcecaoBD;
import lembrete.facade.Facade;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.util.JRLoader;

/**
 * 
 *
 */
public class Report {
	
	/**
	 * Gera um relatorio com a definicao dos grupos em pdf e coloca no response para que o usuario
	 * possa fazer o download.
	 * @param gruposDoUsuario lista de grupos do sistema lembrete
	 */
	public void geraRelatorioGrupos(ArrayList<Grupo> gruposDoUsuario) {
		FacesContext aFacesContext = FacesContext.getCurrentInstance();
        ServletContext context = (ServletContext)aFacesContext.getExternalContext().getContext();
        String realPath = context.getRealPath("/reports/Entradas.jasper");
        String lembretePath = context.getRealPath("/reports/Lembrete.jasper");
		
		JasperReport relatorioJasper = null;  
		try {
			relatorioJasper = (JasperReport) JRLoader.loadObject(lembretePath);
		} catch (JRException e1) {
			e1.printStackTrace();
		}  
	
		RelatorioGrupoDataSource ds = new RelatorioGrupoDataSource(gruposDoUsuario);

		// Parametros do relatorios
		Map parameters = new HashMap();
		parameters.put("SUBREPORT_DIR",realPath+"\\");
		
		
		try {

			//JasperFillManager.fillReportToFile(caminhoRelJasper, parametros, ds);
			JasperPrint jasperPrint = JasperFillManager.fillReport(lembretePath, parameters, ds); 

			/* Exporta para o formato PDF */
       
            ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();  
            JasperExportManager.exportReportToPdfStream(jasperPrint, pdfStream);
            //HTML response  
            HttpServletResponse response = (HttpServletResponse) 
            					FacesContext.getCurrentInstance().getExternalContext().getResponse();  
            response.setContentType("application/octet-stream");  
            response.setHeader("Content-Disposition", "attachment; filename=relatorio.pdf");  
            response.setContentLength(pdfStream.size());     
            
            // Flush pdfStream pra response  
            ServletOutputStream flusher;  
            flusher = response.getOutputStream();  
            pdfStream.writeTo(flusher);   
            flusher.flush();  
            flusher.close();  
            FacesContext.getCurrentInstance().responseComplete();  
            pdfStream.close();   
            pdfStream = null;  

		} catch (JRException e) {
			System.out.println(e.getMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	/**
	 * Gera um relatorio com a agenda do usuario em pdf e coloca no response para que o usuario
	 * possa fazer o download.
	 * @param user o usuario do sistema
	 * @throws ExcecaoBD 
	 */
	public void geraRelatorioAgenda(Usuario user) throws ExcecaoBD {
		FacesContext aFacesContext = FacesContext.getCurrentInstance();
        ServletContext context = (ServletContext)aFacesContext.getExternalContext().getContext();
        String entradasPath = context.getRealPath("/reports/Entradas.jasper");
        String agendaPath = context.getRealPath("/reports/Agenda.jasper");
		
		JasperReport relatorioJasper = null;  
		try {
			relatorioJasper = (JasperReport) JRLoader.loadObject(agendaPath);
		} catch (JRException e1) {
			e1.printStackTrace();
		}  
	
		List entradas = new ArrayList( user.getAgenda().getEntradas().values() );
		//JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(user.getAgenda().getEntradas().values());
		RelatorioAgendaDataSource ds = new RelatorioAgendaDataSource(entradas);

		// Parametros do relatorios
		Map parameters = new HashMap();
		parameters.put("NOME_USUARIO", user.getName());
		parameters.put("EMAIL_USUARIO", user.getEmail());
		
		try {

			//JasperFillManager.fillReportToFile(caminhoRelJasper, parametros, ds);
			JasperPrint jasperPrint = JasperFillManager.fillReport(agendaPath, parameters, ds); 

			/* Exporta para o formato PDF */
       
            ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();  
            JasperExportManager.exportReportToPdfStream(jasperPrint, pdfStream);
            //HTML response  
            HttpServletResponse response = (HttpServletResponse) 
            					FacesContext.getCurrentInstance().getExternalContext().getResponse();  
            response.setContentType("application/octet-stream");  
            response.setHeader("Content-Disposition", "attachment; filename=agenda.pdf");  
            response.setContentLength(pdfStream.size());     
            
            // Flush pdfStream pra response  
            ServletOutputStream flusher;  
            flusher = response.getOutputStream();  
            pdfStream.writeTo(flusher);   
            flusher.flush();  
            flusher.close();  
            FacesContext.getCurrentInstance().responseComplete();  
            pdfStream.close();   
            pdfStream = null;  

		} catch (JRException e) {
			System.out.println(e.getMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
